package logic

import (
	"context"

	"github.com/comfygpt-backend-go/common/consts"
	"github.com/comfygpt-backend-go/common/utils"

	"github.com/comfygpt-backend-go/service/component-rpc/component"
	"github.com/comfygpt-backend-go/service/component-rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListComponentsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListComponentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListComponentsLogic {
	return &ListComponentsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListComponentsLogic) ListComponents(in *component.ListComponentsRequest) (*component.ComponentList, error) {
	// 获取组件列表
	page := int(in.Page)
	offset, limit := utils.PageParam(page, consts.PageSize)

	// 根据page, offset 进行分页查询
	components, err := l.svcCtx.ComponModel.ComponentList(l.ctx, limit, offset)
	if err != nil {
		return &component.ComponentList{}, err
	}

	resp := &component.ComponentList{}
	for _, v := range components {
		item := &component.ComponentItem{
			Id:          v.Id,
			Name:        v.Name,
			Description: v.Description,
			Category:    v.Category,
			Icon:        v.Icon,
			Tags:        utils.StringToArray(v.Tags),
		}
		resp.Components = append(resp.Components, item)
	}

	return resp, nil
}
